import axios from 'axios';
import {
	showTip
} from '../assets/js/tip.js';

export default {
	namespaced: true,
	state: {
		userData: {}
	},
	mutations: {
		isLogin(state, payload) {
			state.userData = payload;
		},
	},
	actions: {
		async login(context, payload) {
			try {
				if (payload.username === '' || payload.password === '') {
					showTip('用户名或者密码不能为空！');
					return;
				}
				const response = await axios({
					method: 'POST',
					url: '/api/user/login',
					data: payload
				});
				if (!response.data.success) {
					showTip('登录失败！' + response.data.message);
					return;
				}
				showTip('登录成功！2s后跳转');
				setTimeout(() => {
					location.href = '/bombpage';
				}, 2000);
			} catch (error) {
				showTip('登录失败！' + error.response.data.message);
				return;
			}
		},
		async isLogin(context) {
			try {
				const response = await axios.get('/api/user/islogin');
				if (!response.data.success) {
					return false;
				}
				context.commit('isLogin', response.data.data);
				return true;
			} catch (error) {
				return false;
			}
		},
		async logout(context) {
			try {
				const response = await axios.get('/api/user/logout');
				if (response.data.success) {
					showTip('退出成功！2s后跳转');
					localStorage.clear();
					setTimeout(() => {
						location.href = '/login';
					}, 2000);
				}
			} catch (error) {
				showTip('失败！' + error.response.data.message);
			}
		}
	}
}